<?php


namespace coco\traits;

/**
 * 单例
 * Trait Singleton
 * @package coco\traits
 */
trait Singleton
{
    private static $instance = [];

    /**
     * @param mixed ...$args
     * @return static
     */
    public static function getInstance(...$args)
    {
        return static::getInstanceByKey('default', $args);
    }

    /**
     * @param string $key
     * @param mixed ...$args
     * @return static
     */
    public static function getInstanceByKey(string $key, array $args = [])
    {
        if (empty(static::$instance[$key])) {
            static::$instance[$key] = new static(...$args);
        }
        return static::$instance[$key];
    }

    public static function free(string $key = 'default')
    {
        unset(static::$instance[$key]);
    }

    private function __clone()
    {
    }

    private function __construct()
    {
    }
}